package com.wyix.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @author wangdx
 * @since 2025/8/6
 */
@Aspect  // 声明为切面
@Component  // 交给Spring管理
public class LogAspect {

    // 定义切点：匹配OrderService的所有方法
    @Pointcut("execution(* com.wyix.service.impl.OrderService.*(..))")
    public void orderPointcut() {
    }

    // 前置通知：方法执行前打印参数
    @Before("orderPointcut()")
    public void before(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("[AOP前置日志] 方法【" + methodName + "】开始执行，参数：" + Arrays.stream(args != null ? args : new Object[0]).map(obj -> obj == null ? "null" : obj.toString()).collect(Collectors.joining(",")));

//        System.out.println("[AOP前置日志] 方法【" + methodName + "】开始执行，参数：" + Arrays.stream(args).map(Object::toString).collect(Collectors.joining(",")));
    }

    // 后置通知：方法执行后打印返回值
    @AfterReturning(pointcut = "orderPointcut()", returning = "result")
    public void afterReturning(Object result) {
        System.out.println("[AOP后置日志] 方法执行完成，返回值：" + result);
    }

    // 异常通知：捕获方法异常
    @AfterThrowing(pointcut = "orderPointcut()", throwing = "ex")
    public void afterThrowing(Exception ex) {
        System.out.println("[AOP异常日志] 方法执行出错：" + ex.getMessage());
    }
}
